/*
 * 应用管理
 */
Ext.define('MyApp.view.AppInfoWindow', {
    extend: 'Ext.window.Window',
    title: '新增/修改应用信息',
    width: 500,
    closeAction: 'hide',
    modal: true,
    form: null,
    getForm: function(){
        var me = this;
        if(me.form==null){
            me.form = Ext.widget('form',{
                layout: 'column',
                defaults: {
                    margin: '10 10 5 5',
                    columnWidth: 1,
                    xtype: 'textfield',
                    labelWidth: 80
                },
                items: [{
                    fieldLabel: '应用名称',
                    name: 'appName',
                    allowBlank: false
                },{
                    fieldLabel: 'LOGO地址',
                    name: 'logoImage',
                    xtype: 'filefield',
                    columnWidth: 1,
				    vtype: 'image'
//                    allowBlank: false
                },{
                    fieldLabel: '访问地址',
                    name: 'url',
                    allowBlank: false
                },{
                    fieldLabel: '详细信息',
                    name: 'descInfo'
                }],
                buttons: [{
                    text:'保存',
                    formBind: true,
					disabled: true,
                    handler: function() {
                    	var tab = Ext.getCmp('appInfoManager'), 
                    	 grid = tab.getAppInfoGrid(),
                    	 userGridStore = grid.getStore(),
                    	 form = me.getForm(),
                            record = form.getRecord(),
                            url = './rs/appinfo/addAppInfo',params,
                            message = '新增';
                        if(!form.isValid()){
                            return;
                        }
                        form.updateRecord(record);
                        var params = record.data;
                        if(me.isUpdate){
                        	url = './rs/appinfo/updateAppInfo';
                        	message = '修改';
                        	Ext.Object.merge(params,{
								'id': record.get('id')
							});
                        }
                        
                        form.submit({
                            url : url,
                            waitMsg: '正在保存。。。',
							params: params,
                            success : function(from, action, json) {
                                var appInfoManager = Ext.getCmp('appInfoManager'),
                                    store = appInfoManager.getStore();
                                Ext.ux.Toast.msg("温馨提示", message + "成功");
                                me.close();
                                store.load();
                            },
                            exception : function(from, action, json) {
                                Ext.ux.Toast.msg("温馨提示", json.responseStatus.message);
                            }
                        });
                    }
                }]
            });
        }
        return this.form;
    },
    isUpdate: null,
    bindData: function(record,isUpdate){
        var me = this,formView=me.getForm(),
            form = formView.getForm();
        form.reset();
        form.loadRecord(record);
        me.isUpdate = isUpdate;
        if(!isUpdate){
            form.reset();
        }
//    	var me = this,
//		form = me.getForm().getForm(),
//		appName = form.findField('appName'),
//		url = form.findField('url'),
//		logUrl = form.findField('logUrl'),
//		descInfo = form.findField('descInfo');
//    	form.reset();
//    	form.loadRecord(record);
    },
    constructor : function(config) {
        var me = this, cfg = Ext.apply({}, config);
        me.items = [me.getForm()]
        me.callParent([ cfg ]);
    }
});


Ext.define('MyApp.view.appInfoManager', {
    extend: 'Ext.panel.Panel',
    id: 'appInfoManager',
    closable: true,
    title: '应用管理',
    queryForm: null,
	getQueryForm: function(){
		var me = this;
		if(me.queryForm==null){
			me.queryForm = Ext.widget('form',{
                layout: 'column',
				defaults: {
					margin: '10 10 10 10',
					xtype: 'textfield'
				},
                items: [{
				    fieldLabel: '应用id',
				    columnWidth: .25,
					labelWidth: 80,
				    name: 'appId'
				},{
				    fieldLabel: '应用名称',
				    columnWidth: .25,
					labelWidth: 80,
				    name: 'appName'
				},{
			        fieldLabel: '创建日期',
			        columnWidth: .5,
					labelWidth: 80,
			        xtype: 'rangedatefield',
			        //起始日期组件的name属性。
			        fromName: 'createStartTime',
			        //终止日期组件的name属性。
			        toName: 'createEndTime'
			    }],
                buttons: [{
					text:'查询',
					handler: function() {
						me.getPagingToolbar().moveFirst();
					}
				},'-',{
					text:'重置',
					handler: function() {
						me.getQueryForm().getForm().reset();
					}
				},'->']
            });
		}
		return this.queryForm;
	},
	store: null,
	getStore: function(){
		var me = this;
		if(me.store==null){
			me.store = Ext.create('MyApp.store.AppInfoStore',{
				autoLoad: true,
				listeners: {
					beforeload : function(store, operation, eOpts) {
						var queryForm = me.getQueryForm();
						if (queryForm != null) {
							var values = queryForm.getValues();
							Ext.apply(operation, {
								params: {
									'createStartTime': values.createStartTime,
									'createEndTime': values.createEndTime,
									'appId': Ext.String.trim(values.appId),
									'appName': Ext.String.trim(values.appName)
								}
							});	
						}
					}
				}
			});
		}
		return me.store;
	},
	pagingToolbar: null,
	getPagingToolbar: function(){
		var me = this;
		if(me.pagingToolbar==null){
			me.pagingToolbar = Ext.widget('pagingtoolbar',{
				store: me.getStore(),
				dock: 'bottom',
				displayInfo: true
			});
		}
		return me.pagingToolbar;
	},
    toolbar: null,
    getToolbar: function(){
        var me = this;
        if(Ext.isEmpty(me.toolbar)){
            me.toolbar = Ext.widget('toolbar',{
                dock: 'top',
                items: [{
                    itemId: 'addButton',
                    text: '注册',
                    listeners: {
                        click: {
                            fn: me.addAppInfo,
                            scope: me
                        }
                    }
                },'-',{
					xtype: 'button',
					itemId: 'editButton',
					text: '编辑',
					listeners: {
						click: {
							fn: me.modifyAppInfo,
							scope: me
						}
					}
				},'-',{
					xtype: 'button',
					itemId: 'enableButton',
					text: '启用',
					listeners: {
						click: {
							fn: me.enableAppInfo,
							scope: me
						}
					}
				},'-',{
					xtype: 'button',
					itemId: 'disableButton',
					text: '禁用',
					listeners: {
						click: {
							fn: me.disableAppInfo,
							scope: me
						}
					}
				},'-',{
                    xtype: 'button',
                    itemId: 'resetKeyButton',
                    text: '重置密钥',
                    listeners: {
                        click: {
                            fn: me.resetAppKey,
                            scope: me
                        }
                    }
                }]
            });
        }
        return me.toolbar;
    },
    appInfoWindow: null,
    getAppInfoWindow: function(){
        if(this.appInfoWindow == null){
            this.appInfoWindow = new MyApp.view.AppInfoWindow();
        }
        return this.appInfoWindow;
    },
    // 新增应用信息
    addAppInfo: function(button, e, eOpts) {
        var window = this.getAppInfoWindow();
        window.bindData(Ext.create('MyApp.model.AppInfoModel'), false);
        window.show();
    },
    // 编辑应用
    modifyAppInfo: function(button, e, eOpts) {
		var grid = this.getAppInfoGrid(),
			selModel = grid.getSelectionModel(),
			selRecords = selModel.getSelection(),
			window = this.getAppInfoWindow();
    	if(selRecords == null||selRecords.length<=0){
    		Ext.ux.Toast.msg("温馨提示", "请先选择要编辑的应用");
    		return;
    	}
    	window.bindData(selRecords[0],true);
		window.show();
    },
    // 禁用应用
    disableAppInfo: function(button, e, eOpts) {
    	var grid = this.getAppInfoGrid(),
			selModel = grid.getSelectionModel(),
			selRecords = selModel.getSelection();
    	if(selRecords == null||selRecords.length<=0){
    		Ext.ux.Toast.msg("温馨提示", "请先选择要禁用的应用");
    		return;
    	}
		var record = selRecords[0];
		if(record.get('isDeleted')){
			Ext.ux.Toast.msg("温馨提示", "该应用已经禁用！");
			return;
		}
    	Ext.MessageBox.confirm('温馨提示', '确定禁用该应用吗？', function(btn){
			if(btn == 'yes'){
				Ext.Ajax.request({
					url : './rs/appinfo/disableAppInfo',
					jsonData: {'id': record.get('id')},
					success : function(response, opts) {
						Ext.ux.Toast.msg("温馨提示", "禁用成功！");
						grid.getStore().load();
						grid.getSelectionModel().deselectAll();
					},
					exception : function(response, opts) {
						var json = Ext.decode(response.responseText);
						Ext.ux.Toast.msg("温馨提示", json.responseStatus.message);
					}
				});
    		}else{
    			return;
    		}
		});
    },
	// 启用应用
    enableAppInfo: function(button, e, eOpts) {
    	var grid = this.getAppInfoGrid(),
			selModel = grid.getSelectionModel(),
			selRecords = selModel.getSelection();
    	if(selRecords == null||selRecords.length<=0){
    		Ext.ux.Toast.msg("温馨提示", "请先选择要启用的应用");
    		return;
    	}
		var record = selRecords[0];
		if(!record.get('isDeleted')){
			Ext.ux.Toast.msg("温馨提示", "该应用已经启用！");
			return;
		}
    	Ext.MessageBox.confirm('温馨提示', '确定启用该应用吗？', function(btn){
			if(btn == 'yes'){
				Ext.Ajax.request({
					url : './rs/appinfo/enableAppInfo',
					jsonData: {'id': record.get('id')},
					success : function(response, opts) {
						Ext.ux.Toast.msg("温馨提示", "启用成功！");
						grid.getStore().load();
						grid.getSelectionModel().deselectAll();
					},
					exception : function(response, opts) {
						var json = Ext.decode(response.responseText);
						Ext.ux.Toast.msg("温馨提示", json.responseStatus.message);
					}
				});
    		}else{
    			return;
    		}
		});
    },
    //重置密钥
    resetAppKey:function(){
    	var grid = this.getAppInfoGrid(),
			selModel = grid.getSelectionModel(),
			selRecords = selModel.getSelection();
		if(selRecords == null||selRecords.length<=0){
			Ext.ux.Toast.msg("温馨提示", "请先选择要重置密钥的应用");
			return;
		}
		var record = selRecords[0];
		Ext.MessageBox.confirm('温馨提示', '确定重置该应用的密钥吗？', function(btn){
			if(btn == 'yes'){
				Ext.Ajax.request({
					url : './rs/appinfo/resetAppKey',
					jsonData: {'id': record.get('id')},
					success : function(response, opts) {
						Ext.ux.Toast.msg("温馨提示", "重置密钥成功！");
						grid.getStore().load();
						grid.getSelectionModel().deselectAll();
					},
					exception : function(response, opts) {
						var json = Ext.decode(response.responseText);
						Ext.ux.Toast.msg("温馨提示", json.responseStatus.message);
					}
				});
			}else{
				return;
			}
		});
    },
	appInfoGrid: null,
	getAppInfoGrid: function(){
		var me = this;
		if(Ext.isEmpty(me.appInfoGrid)){
			me.appInfoGrid = Ext.widget('gridpanel',{
                header: false,
                columnLines: true,
                store: me.getStore(),
				columns: [{
					xtype: 'rownumberer'
				},{
					dataIndex: 'isDeleted',
					text: '是否启用',
					flex: 1,
					align: 'center',
					renderer: function(value, metaData, record, rowIndex, colIndex, store, view) {
		            	return CommonFunction.rendererEnable(value);
		            }
				},{
                    dataIndex: 'appId',
                    sortable: false,
                    flex: 1.4,
                    xtype: 'ellipsiscolumn',
                    align: 'center',
                    text: '应用id'
                },{
                    dataIndex: 'appName',
                    sortable: false,
                    flex: 1.3,
                    xtype: 'ellipsiscolumn',
                    align: 'center',
                    text: '应用名称'
                },{
                    dataIndex: 'logUrl',
                    sortable: false,
                    flex: 1.3,
                    xtype: 'ellipsiscolumn',
                    align: 'center',
                    text: 'LOG地址',
                	xtype: 'tipcolumn', 
					tipConfig: {
						trackMouse: true,
					    hideDelay: 500 
					},
					align: 'center',
					tipBodyElement:'MyApp.view.userAvatarImage',
					flex: 1.5
                },{
                    dataIndex: 'url',
                    sortable: false,
                    flex: 1.3,
                    xtype: 'ellipsiscolumn',
                    align: 'center',
                    text: '应用地址'
                },{
					xtype: 'datecolumn',
					format:'Y-m-d H:i:s',
					dataIndex: 'createTime',
					align: 'center',
					text: '创建时间',
					flex: 1.5
				},{
					xtype: 'datecolumn',
					format:'Y-m-d H:i:s',
					dataIndex: 'lastUpdateTime',
					align: 'center',
					text: '更新时间',
					flex: 1.5
				},{
                	xtype: 'linebreakcolumn',
                    dataIndex: 'descInfo',
                    sortable: false,
                    flex: 3,
                    text: '备注'
                }],
				dockedItems: [me.getPagingToolbar(),me.getToolbar()],
				selModel: Ext.create('Ext.selection.CheckboxModel', {
					allowDeselect: true,
					mode: 'SINGLE'
				})
			});
		}
		return me.appInfoGrid;
	},
    initComponent: function() {
        var me = this;
        Ext.applyIf(me, {
            items: [me.getQueryForm(),me.getAppInfoGrid()]
        });
        me.callParent(arguments);
    }
});
Ext.define('MyApp.view.userAvatarImage', {
	extend : 'Ext.Img',
	src: null,
	height: 64,
	width: 64,
	bindData : function(record, value, metadata, store, view) {
		var me = this;
		if(Ext.isEmpty(record.get('logUrl'))){
			return false;
		}else{
			me.setSrc(record.get('logUrl'));
			return true;			
		}
	},
	constructor : function(config) {
		var me = this, cfg = Ext.apply({}, config);
		me.callParent([ cfg ]);
	}
});